/**
 * create by young (young2f@outlook.com) on 2023/4/16
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const _stringUtils = require('../utils/stringUtils');
const table = 'Store';
const moment = require('moment');
const { result } = require('lodash');
module.exports = class extends base {
  async findMany(body) {
    const { ctx, service } = this;
    const schema = await service.globalService.getModel({ table: 'Store' });
    const query = {};
    _.map(body, (value, key) => {
      const temp = _.find(schema, (it, k) => {
        return k === key;
      });

      if (temp) {
        const { _type } = temp;
        query[key] = this.getValue(_type, value, key);
      }
    });
    const res = await ctx.app.dbs.aggregate(table, [
      { $match: { ...query } },
    ]);
    const result = [];
    _.map(res, item => {
      const { labels } = item;
      _.map(labels, it => {
        _.assign(item, it);
      });
      result.push(item);
    });
    return { status: 'ok', result };
  }

  async assess(body) {
    const { ctx, service } = this;
    const { name, code, spec, number, subcategory, tenantCode } = body;
    const query = { tenantCode };
    if (name) query['name'] = { $regex: name };
    if (code) query['code'] = { $regex: code };
    if (spec) query['spec'] = { $regex: spec };
    if (number) query['number'] = { $regex: number };
    if (subcategory) query['subcategory'] = { $regex: subcategory };

    const res = await ctx.app.dbs.aggregate('ProcureMaterialRecord', [
      { $match: { ...query } },
      { $sort: { createdTs: -1 } },
    ]);
    // return { status: 'ok', result:res};

    let _amount = 0,
      _count = 0;
    _.map(res, item => {
      const { useCount, count, price } = item;
      const c = (count - useCount);
      _amount += c * price;
      _count += c;

    });

    return { status: 'ok', result: { amount: _amount, count: _count } };
  }

  async findOne(body) {
    const { ctx } = this;
    const { code, tenantCode } = body;
    const result = await ctx.app.dbs.findOne('Material', { code, tenantCode });
    return { status: 'ok', result };
  }

  async desktop(body) {
    const { ctx } = this;
    const { tenantCode } = body;
    console.log('tenant code', tenantCode);
    const materialCount = await ctx.app.dbs.count(table, { tenantCode, isDeleted: false });
    console.log('materialCount code', materialCount);
    const storeCountRes = await ctx.app.dbs.aggregate(table, [
      { $match: { tenantCode } },
      {
        $group: {
          _id: null,
          totalCount: { $sum: '$count' }
        }
      }
    ]);
    console.log('storeCountRes code', storeCountRes);
    const amountRes = await ctx.app.dbs.aggregate(table, [
      { $match: { tenantCode } },
      {
        $project: {
          _id: null,
          product: { $multiply: [ '$count', '$price' ] }
        }
      },
      {
        $group: {
          _id: null,
          amount: { $sum: '$product' }
        }
      }
    ]);
    console.log('amount res', amountRes);
    let storeCount = storeCountRes && storeCountRes.length > 0 ? storeCountRes[0].totalCount : 0;
    let amount = amountRes && amountRes.length > 0 ? amountRes[0].amount : 0;
    const result = { materialCount, storeCount, amount };

    return { status: 'ok', result };
  }

  // async outbound(body) {
  //   const { tenantCode, code, outboundDate } = body;
  //
  //   body.outboundOrderCode = code;
  //   const { ctx } = this;
  //   const outboundOrder = await ctx.app.dbs.findOne('OutboundOrder', { tenantCode, code });
  //
  //   const { outboundCount = 0 } = outboundOrder;
  //   const count = parseFloat(outboundCount) + parseFloat(body.outboundCount);
  //   console.log('countt', count);
  //   const res = await ctx.app.dbs.updateOne('OutboundOrder', { tenantCode, code }, {
  //     outboundDate,
  //     outboundCount: count.toFixed(2)
  //   });
  //
  //   body.code = _stringUtils.getCode('OLT');
  //
  //   delete body['_id'];
  //   const result = await ctx.app.dbs.insert('OutboundLot', body);
  //   return { status: 'ok' };
  //
  // }

  async exportExcel(body) {
    const { ctx } = this;
    const res = await this.findMany(body);
    console.log('find many', res);
    const { result } = res;
    const mod = ctx.model['Store'];
    const _header = mod.schema.obj;
    delete _header['tenantName'];
    delete _header['tenantCode'];
    delete _header['createUser'];
    delete _header['createUsername'];
    delete _header['isDeleted'];
    delete _header['isEnabled'];

    delete _header['labels'];
    const header = [];
    _.map(_header, (item, key) => {
      item.title = item.desc;
      item.dataIndex = key;
      item.key = key;
      header.push(item);
    });
    return { status: 'ok', result: { header, data: result } };
  }

  async findDiscardRecordMany(body) {
    const { ctx } = this;
    const {
      key,
      vendor,
      name,
      code,
      procureOrderCode,
      tenantCode,
      createdTs,
    } = body;
    console.log('findDiscardRecordMany body', body);
    const _key = key ? key : 'createdTs';
    const sort = {};
    sort[_key] = -1;
    const query = { tenantCode };

    if (createdTs && createdTs.length > 0) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }


    if (procureOrderCode) query['procureOrderCode'] = { $regex: procureOrderCode };
    if (vendor) query['vendor'] = { $regex: vendor };
    if (name) query['name'] = { $regex: name };
    if (code) query['code'] = { $regex: code };
    console.log('findDiscardRecordMany query', query, sort);
    // const result = await ctx.app.dbs.find('Discard', query,sort);
    const result = await ctx.app.dbs.aggregate('Discard', [
      { $match: { ...query } },
      { $sort: { ...sort } },
    ]);
    return { status: 'ok', result };
  }

  async findDiscardRecord(body) {
    const { ctx } = this;
    const { recordId, tenantCode } = body;

    const result = await ctx.app.dbs.findOne('Discard', { recordId, tenantCode });
    console.log('createDiscardRecord', result);
    return { status: 'ok', result };
  }

  async createDiscardRecord(body) {
    const { ctx } = this;
    const { lotCode, discardCount, tenantCode,code } = body;
    body.recordId = 'DIS' + moment()
      .format('YYYYMMDDHHmmss');
    delete body._id;
    body.createdTs = moment()
      .valueOf();
    const res2 = await ctx.app.dbs.updateOne('InboundLot', {
      lotCode,
      tenantCode
    }, { $inc: { discardCount: discardCount } });
    const res3 = await ctx.app.dbs.updateOne('Material', {
      code,
      tenantCode
    }, { $inc: { storeCount: -discardCount } });
    const result = await ctx.app.dbs.insert('Discard', body);
    // console.log('createDiscardRecord body', body);
    return { status: 'ok', result };
  }

  async deleteDiscardRecord(body) {
    const { ctx } = this;
    const { lotCode, recordId, discardCount, tenantCode } = body;

    const res2 = await ctx.app.dbs.updateOne('InboundLot', {
      lotCode,
      tenantCode
    }, { $inc: { discardCount: -discardCount } });
    const result = await ctx.app.dbs.deleteOne('Discard', { recordId, tenantCode });
    // console.log('createDiscardRecord body', body);
    return { status: 'ok', result };
  }

  async reviewDiscardRecord(body) {
    const { ctx } = this;
    const { recordId, tenantCode, reviewStatus } = body;

    const result = await ctx.app.dbs.updateOne('Discard', { recordId, tenantCode }, { reviewStatus });
    // console.log('createDiscardRecord body', body);
    return { status: 'ok', result };
  }
};
